import { defineStore } from 'pinia'
import axios from 'axios'
import { useUserStore } from './user'

export const useCartStore = defineStore('cart', {
  state: () => ({
    cartItems: [],
    currentBusinessId: null
  }),

  getters: {
    totalCount: (state) => {
      return state.cartItems.reduce((total, item) => total + item.quantity, 0)
    },
    totalPrice: (state) => {
      return state.cartItems.reduce((total, item) => {
        return total + (item.food?.foodPrice || 0) * item.quantity
      }, 0)
    }
  },

  actions: {
    async getCartItems(businessId) {
      const userStore = useUserStore()
      if (!userStore.isLoggedIn()) return
      
      try {
        const res = await axios.get('/cart/listCart', {
          params: {
            userId: userStore.userId,
            businessId
          }
        })
        this.cartItems = res.data
        this.currentBusinessId = businessId
      } catch (error) {
        console.error('获取购物车失败:', error)
      }
    },

    async clearCart() {
      this.cartItems = []
      this.currentBusinessId = null
    }
  }
})